package scheduler

import "crawler/engine"

type QueuedSchedluer struct {
	requestChan chan engine.Request			// 请求通道，将请求发送给任务工作者通道
	workerChan  chan chan engine.Request	// 任务工作者通道
}

func (s *QueuedSchedluer) WorkerChan() chan engine.Request {
	return make(chan engine.Request)
}

func (s *QueuedSchedluer) Submit(r engine.Request) {
	s.requestChan <- r
}

func (s *QueuedSchedluer) WorkerReady(w chan engine.Request) {
	s.workerChan <- w
}

func (s *QueuedSchedluer) Run() {
	s.requestChan = make(chan engine.Request)
	s.workerChan = make(chan chan engine.Request)
	go func() {
		var requestQ []engine.Request
		var workerQ []chan engine.Request
		for {
			var activeRequest engine.Request
			var activeWorker chan engine.Request
			if len(requestQ) > 0 && len(workerQ) > 0 { // 既有request，又有worker，可以将rquest放到worker中工作
				activeRequest = requestQ[0]
				activeWorker = workerQ[0]
			}

			select {
			case r := <-s.requestChan:
				requestQ = append(requestQ, r)
			case w := <-s.workerChan:
				workerQ = append(workerQ, w)
			case activeWorker <- activeRequest:		// 将request送给work工作
				workerQ = workerQ[1:]
				requestQ = requestQ[1:]
			}
		}
	}()
}
